package com.coder.algorithm.leetcode

import com.coder.algorithm.struct.ListNode

/**
 * [61. 旋转链表](https://leetcode-cn.com/problems/rotate-list/)
 *
 * 提示：
 * - 链表中节点的数目在范围 [0, 500] 内
 * - -100 <= Node.val <= 100
 * - 0 <= k <= 2 * 109
 *
 * @author yuhus
 * @date: 2022/4/14
 */
object l_0061 {
    fun rotateRight(head: ListNode?, k: Int): ListNode? {
        if (k == 0 || head?.next == null) {
            return head
        }
        var n = 1
        var cur = head
        while (cur?.next != null) {
            n++
            cur = cur.next
        }
        // 向左移动 left 个位置
        var left = n - k % n
        if (left == n) {
            return head
        }
        // cur 为尾节点
        cur?.next = head
        while (left > 0) {
            left--
            cur = cur?.next
        }
        val newHead = cur?.next
        cur?.next = null
        return newHead
    }
}